package Pipe;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.io.PrintWriter;
import java.util.Scanner;

public class Pipe {
    //输入管道
    private Scanner pipeReader;
    //输出管道
    private PrintWriter pipeWriter;

    public Pipe(){
        PipedWriter pw = new PipedWriter();
        PipedReader pr = new PipedReader();
        try{
            // 将此管道写入器连接到接收器
            pw.connect(pr);
        } catch (IOException e){
            e.getMessage();
        }
        pipeWriter = new PrintWriter(pw);
        pipeReader = new Scanner(pr);
    }

    //读入一行数据到管道
    //@return 读入的数据
    public String readerLine() throws IOException{
        if (pipeReader.hasNextLine()) {
            return pipeReader.nextLine();
        }
        return null;
    }

    //从管道输出一行数据
    public void writerLine(String strline) throws IOException{
        pipeWriter.println(strline);
    }
    //将读管道关闭，调用该方法后，不能再从管道中读数据
    public void closeReader() throws IOException{
        pipeReader.close();
    }

    //先刷新数据，在将写管道关闭，调用该方法后，不能向管道中写数据
    public void closeWriter() throws IOException{
        pipeWriter.flush();
        pipeWriter.close();
    }
}

